<template>
  <div>
    <!-- prettier-ignore -->
    <el-drawer :visible.sync="drawer.成交登记.visible" :wrapperClosable="false" :close-on-press-escape="false" @open="open" @close="close" :size="'480px'">
      <div slot="title" class="align-cm">
        <b class="fc-gray10">成交登记</b>
      </div>
      <!-- <pre>{{ formatParameter }}</pre> -->
      <!-- <pre>{{ form}}</pre> -->
      <!-- style="margin-left: 880px" -->

      <el-form label-width="120px" size="small" class="form" :model="form" ref="form" :rules="rules">
        <el-form-item v-for="(item, idx) in form.phone" :key="idx"
          :label="`手机号${idx + 1}`" :prop="'phone[' + idx + '].value'" :rules="rules.phone">
          <el-input v-model="item.value">
            <template slot="append" v-if="idx > 0"><el-button @click="splicePhone(idx)" icon="el-icon-delete"></el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="form.phone.length < MAXPHONE">
          <el-button type="primary" icon="el-icon-plus" @click="pushPhone">添加手机号</el-button>
        </el-form-item>
        <el-form-item v-if="form.phone.length >= 1 && allowGetCallLog">
          <div slot="label">添加录音</div>
          <div class="mb10" v-if="form.录音记录.length>=1">
            <el-tag v-for="(v,k) in form.录音记录.slice(0,3)" :key="k">{{ v.callId }}</el-tag>
            <el-tag v-if="form.录音记录.length > 3">+{{ form.录音记录.length - 3  }}</el-tag>
          </div>
          <el-button type="primary" @click="getSoundRecord">检索录音记录</el-button>
        </el-form-item>
        <el-form-item label="客户姓名" prop="客户姓名" :rules="rules.name">
          <el-input v-model="form.客户姓名"></el-input>
        </el-form-item>
        <!-- <pre>{{conditional.订单类型.options}}</pre> -->
        <el-form-item label="订单类型" prop="订单类型" :rules="rules.select">
          <el-select class="w100" placeholder="请选择" v-model="form.订单类型" @change="form.版本价格=''">
            <el-option v-for="item in conditional.订单类型.options.filter((v)=>{
              return !v.disabled
            })"
              :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" >{{item.label}}
            </el-option>
          </el-select>
        </el-form-item>
       
        <el-form-item label="版本/价格" prop="版本价格" :rules="rules.select">
          <el-select class="w100" placeholder="请选择" v-model="form.版本价格" @change="setMoney($event)" >
            <el-option v-for="item in filterCrmProductByOrderTpye"
              :key="item.value" :label="item.label" :value="item.value">{{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <pre>{{conditional.crmProduct.options}}</pre> -->
        <!-- <pre>{{filterCrmProductByOrderTpye}}</pre> -->

        <el-form-item label="成交时间" prop="成交时间" :rules="rules.time">
          <el-date-picker type="datetime" style="width: 100%" v-model="form.成交时间" placeholder="请选择"> </el-date-picker>
        </el-form-item>
        <el-form-item label="成交金额" prop="成交金额" :rules="rules.number">
          <el-input v-model="form.成交金额"></el-input>
        </el-form-item>
        <el-form-item label="进线渠道" prop="进线渠道" :rules="rules.select">
          <el-select class="w100" placeholder="请选择" filterable v-model="form.进线渠道">
            <el-option v-for="item in conditional.resourceChannels.options.slice(1)"
              :key="item.value" :label="item.label" :value="item.value">{{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进线时间" prop="进线时间">
          <el-date-picker type="datetime" style="width: 100%" disabled v-model="form.进线时间" placeholder="请选择" ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="第一次进线">
            <el-date-picker type="datetime" style="width: 100%" v-model="form.第一次进线" placeholder="请选择">
            </el-date-picker>
          </el-form-item> -->
        <el-form-item label="资金量" prop="资金量" :rules="rules.select">
          <el-select class="w100" v-model="form.资金量">
            <el-option value="1" label="5万以下"></el-option>
            <el-option value="2" label="15-30万"></el-option>
            <el-option value="3" label="30-50万"></el-option>
            <el-option value="4" label="50-100万"></el-option>
            <el-option value="5" label="100万以上"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="支付方式" :rules="rules.select">
          <el-select class="w100" placeholder="请选择" multiple collapse-tags filterable v-model="form.支付方式">
            <el-option v-for="item in conditional.payType.options.slice(1)"
              :key="item.key" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客服企微" prop="客服企微" :rules="rules.select">
          <el-select class="w100" placeholder="请选择" v-model="form.客服企微">
            <el-option v-for="item in conditional.workbench.options.slice(1).filter((v)=>{
              return !v.isHidden
            })"
              :key="item.key" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报表绑定" prop="报表绑定">
          <el-select class="w100" placeholder="请选择" v-model="form.报表绑定">
            <el-option v-for="item in rfList"
              :key="item.key" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="直播间账号绑定" prop="直播间账号绑定">
          <el-select class="w100" placeholder="请选择" v-model="form.直播间账号绑定" filterable>
            <el-option v-for="item in 直播间账号list"
              :key="item.key" :label="item.label" :value="item.value">
              {{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成交信息圖片" prop="成交信息圖片" v-show="false">
          <!-- <pre>{{  fileUploadList.map((v)=>{return v.response}) }}</pre> -->
          <el-upload ref="upload2" multiple :action="serverUrl" :data="TokenQiNiu"
            :before-upload="uploadBefore"
            :http-request="uploadFile"
            :on-success="uploadSuccess2"
            :on-error="uploadError"
            :on-remove="handleRemove"
            list-type="picture" :file-list="fileUploadList2">
            <el-button type="primary" icon="el-icon-plus">选择图片</el-button>
          </el-upload>
          <!-- {{ TokenQiNiu }} -->
          <el-button class="pos-after" icon="el-icon-delete" @click="clearFiles2">清空重选</el-button>
        </el-form-item>
        <el-form-item label="汇款单" prop="汇款单">
          <!-- <pre>{{  fileUploadList.map((v)=>{return v.response}) }}</pre> -->
          <el-upload ref="upload" multiple :action="serverUrl" :data="TokenQiNiu"
            :before-upload="uploadBefore"
            :http-request="uploadFile"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-remove="handleRemove"
            list-type="picture" :file-list="fileUploadList">
            <el-button type="primary" icon="el-icon-plus">选择图片</el-button>
          </el-upload>
          <!-- {{ TokenQiNiu }} -->
          <el-button class="pos-after" icon="el-icon-delete" @click="clearFiles">清空重选</el-button>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.备注"></el-input>
        </el-form-item>

        <div class="align-rm">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submit()">确定</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { bus } from '@/main.js';
import * as qiniu from 'qiniu-js';
import { mapState, mapMutations } from 'vuex';
export default {
  name: 'clinchADealTheRegistratio',

  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      serverUrl: 'http://upload.qiniup.com', //上传图片的地址
      qiniuAddress: 'http://qiniuoss.chenxi618.com',
      TokenQiNiu: { token: '', key: '' },
      fileUploadList: [],
      fileUploadList2: [],

      MAXPHONE: 3,
      form: {
        phone: [{ value: '' }],
        录音记录: [],
        客户姓名: '',
        订单类型: 1,
        版本价格: '',
        成交时间: '',
        成交金额: '',
        进线渠道: '',
        进线时间: '',
        第一次进线: '',
        资金量: '',
        支付方式: [],
        客服企微: '',
        报表绑定: 0,
        直播间账号绑定: 0,
        汇款单: '',
        备注: '',
      },
      rfList: [],
      直播间账号list: [],
      tempUrl: '',
      optSoundRecord: [
        {
          callId: 0,
          callTime: '',
          realName: '',
          remark: '',
          lastCallLengthString: '',
          soundState: 0,
          soundAddress: '',
        },
      ],
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      dialog: {
        loading: false,
        visible: false,
      },
      rules: {
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {
            pattern: /^\d{11}$/,
            message: '电话号码格式不正确',
            trigger: 'blur',
          },
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        select: [{ required: true, message: '请选择', trigger: 'change' }],
        time: [{ required: true, message: '请输入时间', trigger: 'blur' }],
        number: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapState(['userInfo', 'conditional', 'drawer']),

    allowGetCallLog: function() {
      let value = this.form.phone[0].value;
      return this.rules.phone[1].pattern.test(value);
    },
    filterCrmProductByOrderTpye: function() {
      let _ = this._;
      let value = this.form.订单类型;
      let oArr = this.conditional.crmProduct.options.slice(1);
      return oArr.filter(v => {
        let a = v.beLongTo.length > 0;
        let b = _.includes(v.beLongTo, value);
        return a && b;
      });
    },
    formatParameter: function() {
      let s = _.get(this.drawer, '成交登记.temp');
      let p = this.form;
      return {
        pN_Resources_Id: _.get(s, 'pn_Resources_Id', '0'), //约定；约定作废；重新尝试获取并提交
        Scrm_Follow_User_Id: _.get(s, 'id', ''), //integer($int32) 资源id
        crM_Product_Id: _.get(p, '版本价格', ''), //integer($int32) CRM产品表id / “版本/价格”
        company_Employee_Id: (ceid => {
          if (typeof ceid != 'number') {
            return this.userInfo.company_Employee_Id;
          } else {
            return ceid;
          }
        })(_.get(s, 'company_Employee_Id', '')), //integer($int32) 销售

        phoneNumber: _.get(p, 'phone[0].value', ''), //string 手机号
        phoneNumber1: _.get(p, 'phone[1].value', ''), //string 第二号码
        phoneNumber2: _.get(p, 'phone[2].value', ''), //string 第三号码
        showPhoneNumber: '', //string（不知道是干嘛的）
        customerName: _.get(p, '客户姓名', ''), // string客户姓名

        trading_Time: (t => {
          return this.$moment(t).isValid()
            ? this.$moment(t).format('YYYY-MM-DD HH:mm:ss')
            : '';
        })(_.get(p, '成交时间', '')), //string($date-time) 成交时间
        // trading_TimeString: "", // string 成交时间字符串（完全不需要）
        moneys: _.get(p, '成交金额', 0), //number($double) 成交金额

        qudao: _.get(p, '进线渠道', ''), // string渠道
        // lastJxQuDao: _.get(p, "进线渠道", []).join(","), // string渠道
        // lastJxQuDaoId: _.get(p, "进线渠道", []).join(","), // string最后进线渠道id
        // jxTime: "", // string($date-time)进线时间
        // jxTimeString: "", // 添加时间字符串（完全不需要）
        lastJxTime: '', // string($date-time)进线时间
        // lastJxTimeString: "", // 最后进线时间（完全不需要）

        inComingTime: (t => {
          return this.$moment(t).isValid()
            ? this.$moment(t).format('YYYY-MM-DD HH:mm:ss')
            : '';
        })(_.get(p, '进线时间', '')), // string($date-time)进线时间
        // first_InTime: ((t) => {
        //   return t == "" ? "" : this.$moment(t).format("YYYY-MM-DD HH:mm:ss");
        // })(_.get(p, "第一次进线", "")), // string($date-time)第一次进线时间
        // first_InTimeString: "", //添加时间字符串（完全不需要）

        amountOfFunds: _.get(p, '资金量', 0), // integer($int32)资金量

        payTypes: _.get(p, '支付方式', []).join(','), // string 支付方式 用 , 间隔
        customerServiceEsCompanyId: _.get(p, '客服企微'),
        picList: this.fileUploadList
          .map(v => {
            let fileName = this._.get(v, 'response.key');
            return `${this.qiniuAddress}/${fileName}`;
          })
          .join(','), // string 付款截图 用 | 间隔
        tradingImgUrl: this.fileUploadList2
          .map(v => {
            let fileName = this._.get(v, 'response.key');
            return `${this.qiniuAddress}/${fileName}`;
          })
          .join(','), // string 付款截图 用 | 间隔
        trading_Remark: _.get(p, '备注', ''), // string 成交备注
        /* 以上是设计图上有的字段 */

        // addTime: "", // string($date-time) 添加时间
        // addTimeString: "", // 添加时间字符串（完全不需要）
        // editTime: "", // string($date-time)修改时间
        smallProductDesc: '', // string小产品分类
        bigProductDesc: '', // string大产品分类
        realName: _.get(s, 'realName', ''), // string销售名称
        fromSource_Id: _.get(s, 'fromSource_Id', ''), // integer($int32)来源id
        es_Company_Id: _.get(s, 'eS_Company_Id', ''), // string公司企微id
        external_userid: _.get(s, 'external_userid', ''),
        unionid: _.get(s, 'unionid', ''),
        customer_Order_Type_Id: _.get(p, '订单类型', 1), // integer($int32) 订单类型

        soundAddress: _.get(p, '录音记录', [])
          .map(v => {
            return v.url;
          })
          .join(','), //callID
        report_Id: _.get(p, '报表绑定', 0),
        scrm_Zhibo_Users_Id: _.get(p, '直播间账号绑定', 0),
      };
    },
  },
  methods: {
    ...mapMutations(['toggleDialog']),
    open: function() {
      let s = _.get(this.drawer, '成交登记.temp');
      if (_.has(s, 'allPhoneNumber[0].phoneNumber')) {
        this.form.phone[0].value = _.get(
          s,
          'allPhoneNumber[0].phoneNumber',
          '',
        );
      }
      if (_.has(s, 'allPhoneNumber[1].phoneNumber')) {
        this.form.phone.push({
          value: _.get(s, 'allPhoneNumber[1].phoneNumber', ''),
        });
      }
      if (_.has(s, 'allPhoneNumber[2].phoneNumber')) {
        this.form.phone.push({
          value: _.get(s, 'allPhoneNumber[2].phoneNumber', ''),
        });
      }
      this.form.进线时间 = _.get(s, 'addTime', '');
      this.form.成交时间 = this.$moment().format('YYYY-MM-DD HH:mm:ss');
      this.form.客服企微 =
        _.cloneDeep(this.conditional.workbench.DEFAULT) || '';
      this.$api
        .获取外部联系人信息成交信息(
          {
            scrm_Follow_User_Id: s.id,
          },
          {},
        )
        .then(res => {
          if (res.code == 200) {
            return Promise.resolve(res.data);
          }
        })
        .then(res => {
          this.form.进线渠道 = this._.get(res, 'fromSource_Id', '');
        });
      this.$api.报表
        .成交报表信息下发(
          {
            company_Employee_Id: this.$store.getters['userInfo/getEmployee']
              .company_Employee_Id,
            es_Company_Id: s.eS_Company_Id,
            external_Userid: s.external_userid,
          },
          {},
        )
        .then(res => {
          if (res.code == 200 && res.data.length > 0) {
            this.rfList.splice(0, this.rfList.length);
            res.data.forEach(v => {
              this.rfList.push({
                key: v.report_Id,
                label: v.report_Id + ':' + v.title,
                value: v.report_Id,
              });
            });
          }
          // rfList
        })
        .catch(err => {})
        .finally(_ => {});
      this.$api.直播间
        .直播间账号列表下发(
          {
            company_Employee_Id: this.$store.getters['userInfo/getEmployee']
              .company_Employee_Id,
          },
          {},
        )
        .then(res => {
          this.直播间账号list.splice(0, this.直播间账号list.length);
          res.data.forEach(v => {
            let label = (v => {
              return [v.user_Name, v.user_NickName, v.user_Remark]
                .filter(str => {
                  return this._.isString(str);
                })
                .join('-');
            })(v);
            this.直播间账号list.push({
              key: v.user_Id,
              label: label,
              value: v.user_Id,
            });
          });
        })
        .catch(err => {
          console.error(err);
        })
        .finally(_ => {});
    },
    close: function() {
      // this.form.phone[0].value = "";
      this.$refs.form.resetFields();
      this.$set(this.form.phone[0], 'value', '');
      this.splicePhone(2);
      this.splicePhone(1);
      this.fileUploadList.splice(0, this.fileUploadList.length);
      this.fileUploadList2.splice(0, this.fileUploadList2.length);
      this.form.录音记录.splice(0, this.form.录音记录.length);
      // this.$set(this, 'form', this.$options.form);
      this.form.备注 = '';
    },
    /* 手机号需要点操作 s */
    pushPhone: function() {
      let tar = this.form.phone;
      if (tar.length <= 0 || tar.length >= this.MAXPHONE) {
        return;
      }
      tar.push({ label: '', value: '' });
    },
    splicePhone: function(idx) {
      let tar = this.form.phone;
      if (tar.length <= 1 || tar.length > this.MAXPHONE) {
        return;
      }
      tar.splice(idx, 1);
    },
    /* 手机号需要点操作 e */
    setMoney: function(e, a, b) {
      let opts = this.conditional.crmProduct.options;
      let item = opts.find(v => {
        return v.value == e;
      });
      this.form.成交金额 = _.get(item, 'money', 0);
    },

    cancel: function() {
      this.toggleDialog({
        type: 'drawer',
        key: '成交登记',
        tempData: null,
      });
    },
    submit: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let p = this.formatParameter;
          let d = { companyEmployeeId: this.userInfo.company_Employee_Id };
          this.$api
            .savePNResourcesTrading(d, p)
            .then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '登记成功',
                  type: 'success',
                });
                this.toggleDialog({
                  type: 'drawer',
                  key: '成交登记',
                  tempData: null,
                });
                this.$refs.form.resetFields();
                bus.$emit('成交登记变更', {});
              } else {
                return Promise.reject(res.message);
              }
            })
            .catch(err => {
              this.$message({
                message: err,
                type: 'error',
              });
            });
        }
      });
      return;
    },
    /* 上传图片相关 s */
    clearFiles() {
      this.$refs.upload.clearFiles();
      this.fileUploadList.splice(0, this.fileUploadList.length);
    },
    clearFiles2() {
      this.$refs.upload2.clearFiles();
      this.fileUploadList2.splice(0, this.fileUploadList2.length);
    },
    uploadBefore(file) {
      if (file.type != 'image/png' && file.type != 'image/jpeg') {
        this.$message({
          message: '请上传正确的图片',
          type: 'warning',
        });
        return false;
      }
    }, // 上传之前回调
    uploadFile(elUpload) {
      return this.$api.getQiniuToken().then(res => {
        let token = res.data;
        let match = elUpload.file.name.match(/([^\/]+)\.(\w+)$/);
        let newFileName = `${this.$mock.mock('@uuid')}.${match[2]}`;

        let config = {
          useCdnDomain: true, //是否使用七牛的CDN加速域名上传，默认为false，上传后获取的文件地址为七牛存储空间的原始URL。
          region: qiniu.region.z0, //指定文件上传的区域，例如z0:华东,z1:华北,z2:华南,na0:北美。
        };
        let putExtra = {
          fname: newFileName, //用于指定上传的文件名，如果不指定，则默认使用上传文件的原始文件名。
          params: {}, //用于指定上传文件的扩展参数，例如文件类型、文件大小、上传时间等。
        };
        let key = newFileName;
        let observable = qiniu.upload(
          elUpload.file,
          key,
          token,
          putExtra,
          config,
        );
        return new Promise((resolve, reject) => {
          observable.subscribe({
            next(res) {
              // console.log(res);
            },
            error(err) {
              reject(err);
            },
            complete(res) {
              resolve(res);
            },
          });
        });
      });
    },

    uploadSuccess(response, file, fileList) {
      this.fileUploadList = fileList;
    }, // 上传成功
    uploadSuccess2(response, file, fileList) {
      this.fileUploadList2 = fileList;
    }, // 上传成功
    uploadError() {
      this.$message.error(`图片上传失败`);
      return;
    },
    handleRemove(file, fileList) {
      this.fileUploadList = fileList;
    },
    /* e 上传图片相关 */
    getSoundRecord() {
      let tempData = this._.get(this.drawer, '成交登记.temp');
      Object.assign(tempData, {
        phoneNumber: _.get(this.form, 'phone[0].value', ''), //string 手机号//测试用: 13800001111
        phoneNumber1: _.get(this.form, 'phone[1].value', ''), //string 第二号码
        phoneNumber2: _.get(this.form, 'phone[2].value', ''), //string 第三号码
      });
      let tempList = this._.get(this.form, '录音记录', []);
      // this.dialog.visible = true;
      bus.$emit('查看录音', {
        tempData: tempData,
        tempList: tempList,
      });
    }, //打开弹窗检索录音记录

    try2play(item) {
      this.optSoundRecord.forEach(v => {
        if (v != item) {
          v.soundState = 0;
        }
      });
      if (item.soundState == 0) {
        this.tempUrl = item.soundAddress;
        this.$refs.audio.play();
        item.soundState = 2;
      } else {
        this.tempUrl = '';
        this.$refs.audio.pause();
        item.soundState = 0;
      }
      this.$refs.audio.onended = event => {
        item.soundState = 0;
      };
    },
  },
  mounted: function() {
    bus.$on('增减tempList', e => {
      if (e.action == 'add') {
        this.form.录音记录.push({
          callId: e.callId,
          url: e.url,
        });
      }
      if (e.action == 'remove') {
        let idx = this.form.录音记录.findIndex(v => {
          return v.callId == e.callId;
        });
        this.form.录音记录.splice(idx, 1);
      }
    });
    // this.$api.getQiniuToken().then((res) => {
    //   if (res.code == 200) {
    //     this.qiniu.token = res.data;
    //   }
    // });
  },
};
</script>

<style scoped lang="less" src="./chengjiaodengji.less"></style>
